<?php
namespace app\controller;

use app\Request;

use app\service\AliyunOss as OssService;

use think\exception\HttpResponseException;
use think\Response;
/**
 * @author yanxusheng <[<ausheng@foxmail.com>]>
 * @datetime 2023/3/21 17:05
 * @content 图片上传、等等公共方法
 */
class Communal
{
    public string $field = 'room_code, player_code, master, rank, seat, identity, task, career_name, career, transfer, win, status, create_time';


    // 第三方登陆
    public function callBack(Request $request) {
        $params = $request->param();

        trace(json_encode($params), 'info');

        $this->success($params);
    }



    public function OssStsToken() {
        // 应该再写一个黑名单
        $credentials = OssService::main();
        if (!is_object($credentials) && !is_array($credentials)) {
            $this->error($credentials);
        }
        $this->success($credentials);
    }




    /**
     * 操作成功返回的数据.
     *
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int $code   错误码，默认为1
     * @param string $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function success($data = null, string $msg = 'SUCCESS', int $code = 200, $type = null, array $header = [])
    {
        if (!empty($data['task'])) {
            $data['task'] = json_decode($data['task'], true);
        }

        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据.
     *
     * @param string $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int $code   错误码，默认为0
     * @param string|null $type   输出类型
     * @param array  $header 发送的 Header 信息
     */
    protected function error(string $msg = '', $data = null, int $code = -1, string $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端.
     *
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int $code   错误码，默认为0
     * @param string|null $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     *
     * @return void
     *@throws HttpResponseException
     */
    protected function result($msg, $data = null, int $code = 0, string $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => time(),
            'data' => $data,
            'VERSION' => env('app.app_version', '1.0.0'),
        ];

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, 'json', $code)->header($header);
        //halt($response);
        throw new HttpResponseException($response);
    }
}